<template>
  <div class="addPersonnel-container-padding">
    <div v-if="!disabled" class="buttonList">
      <el-button type="primary" @click="save">保存为草稿</el-button>
      <el-button type="primary" @click="submit">提交</el-button>
    </div>
    <div class="card">
      <div class="title">人员基本信息</div>
      <el-form
        ref="baseInfoRef"
        :inline="true"
        :model="userBaseInfo"
        :rules="rules"
        :disabled="disabled"
        class="demo-form-inline"
        label-width="auto"
      >
        <el-form-item label="专家名称：" prop="name">
          <el-input
            v-model="userBaseInfo.name"
            placeholder="请输入"
            clearable
          />
        </el-form-item>
        <el-form-item label="性别：">
          <el-select v-model="userBaseInfo.gender" placeholder="请选择">
            <el-option
              v-for="item in dictStore.getDictType('system_user_sex')"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="出生年月：" prop="birthDate">
          <el-date-picker
            v-model="userBaseInfo.birthDate"
            type="date"
            placeholder="请选择"
            clearable
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            style="width: 323px"
          />
        </el-form-item>
        <el-form-item label="政治面貌：">
          <el-select
            v-model="userBaseInfo.politicalAffiliation"
            placeholder="请选择"
          >
            <el-option
              v-for="item in politicalStatus"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="联系电话：" prop="mobile">
          <el-input
            v-model="userBaseInfo.mobile"
            placeholder="请输入"
            clearable
          />
        </el-form-item>
      </el-form>
    </div>
    <div class="card margin-top20">
      <div class="title">专家信息</div>
      <el-form
        ref="onlineInfoRef"
        :inline="false"
        :model="userBaseInfo"
        :rules="rules"
        :disabled="disabled"
        class="demo-form-inline"
        label-width="auto"
      >
        <el-form-item label="单位名称：">
          <el-input
            v-model="userBaseInfo.unitName"
            placeholder="请输入"
            clearable
          />
        </el-form-item>
        <el-form-item label="主研方向1：">
          <el-input
            v-model="userBaseInfo.majorStudyOne"
            placeholder="请输入"
            clearable
          />
        </el-form-item>
        <el-form-item label="主研方向2：">
          <el-input
            v-model="userBaseInfo.majorStudyTwo"
            placeholder="请输入"
            clearable
          />
        </el-form-item>
        <el-form-item label="主研方向3：">
          <el-input
            v-model="userBaseInfo.majorStudyThree"
            placeholder="请输入"
            clearable
          />
        </el-form-item>
        <!-- <el-form-item
          v-for="(item, index) in userBaseInfo.mainResearchList"
          :key="index"
          :label="'主研方向' + (index + 1) + '：'"
          :rules="{ required: true, message: '不能为空', trigger: 'blur' }"
        >
          <el-input v-model="item.value" placeholder="请输入" clearable />
          <el-button
            v-if="index !== 0"
            class="margin-left20"
            type="danger"
            :icon="Delete"
            circle
            @click.prevent="removeMainResearch(index)"
          />
          <el-button
            v-if="index == 0"
            class="margin-left20"
            type="primary"
            :icon="Plus"
            text
            @click="addMainResearch"
          >
            增加主研方向
          </el-button>
        </el-form-item> -->
        <el-form-item label="最高学位：">
          <el-select v-model="userBaseInfo.highestDegree" placeholder="请选择">
            <el-option
              v-for="item in selectOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="专业技术职务：">
          <el-select
            v-model="userBaseInfo.technicalPosition"
            placeholder="请选择"
          >
            <el-option
              v-for="item in selectMajorOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="专家类别：">
          <el-select v-model="userBaseInfo.expertType" placeholder="请选择">
            <el-option
              v-for="item in selectExpertCategory"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup lang="ts">
  import {
    reactive,
    ref,
    withDefaults,
    defineProps,
    watch,
    onMounted,
  } from 'vue'
  import type { FormRules, FormInstance } from 'element-plus'
  // import { Delete, Plus } from '@element-plus/icons-vue'
  import { useRouter, useRoute } from 'vue-router'
  import { useDictStore } from '@/store/modules/dict'
  import {
    operationLog,
    selectOptions,
    selectMajorOptions,
    selectExpertCategory,
    politicalStatus,
  } from '../table/column'
  import { VxeGridProps, VxePagerEvents } from 'vxe-table'
  import { addReview, getReviewsInfo, updateReview } from '@/api/reviewExperts'
  import { postDraftBoxCreate } from '@/api/project/drafts'
  import { isPhone } from '@/utils/validate'
  import { useCloseTabNavigate } from '@/utils/useCloseTabNavigate'

  const props = withDefaults(
    defineProps<{
      disabled?: boolean
      operation?: boolean
      userInfo?: any
    }>(),
    {
      disabled: false,
      operation: false,
      userInfo: {},
    }
  )

  const { closeTabNavigate } = useCloseTabNavigate()
  const dictStore = useDictStore()
  const route = useRoute()

  const baseInfoRef = ref<FormInstance>()
  const onlineInfoRef = ref<FormInstance>()

  const userBaseInfo = reactive({
    name: '',
    gender: '',
    birthDate: '',
    politicalAffiliation: '',
    mobile: '',
    unitName: '',
    majorStudyOne: '',
    majorStudyTwo: '',
    majorStudyThree: '',
    highestDegree: '',
    technicalPosition: '',
    expertType: '',
  })

  watch(
    () => props.userInfo,
    (newval) => {
      for (const key in newval) {
        userBaseInfo[key] = newval[key]
      }
    },
    { deep: true }
  )

  const validatePhone = (rule, value, callback) => {
    if (value && !isPhone(value)) {
      callback(new Error('请输入正确的手机号'))
    } else {
      callback()
    }
  }

  const rules = reactive<FormRules>({
    name: [
      // { required: true, message: '请输入正确的名称', trigger: 'blur' },
      // { min: 2, max: 5, message: '请输入 3 到 5 个字', trigger: 'blur' },
    ],
    mobile: [{ validator: validatePhone, trigger: 'blur' }],
  })

  const emeit = defineEmits<{
    (event: 'stop', data: boolean): void
  }>()

  // 保存为草稿
  const save = async () => {
    emeit('stop', true)
    try {
      const params = {
        id: route.query.id || '',
        type: 'REVIEW_EXPERT',
        submitJson: JSON.stringify({
          ...userBaseInfo,
          draftBoxId: route.query?.id || '',
        }),
      }
      const res: any = await postDraftBoxCreate(params)
      if (res && res.code === 0) {
        ElMessage.success('保存草稿成功')
        baseInfoRef.value.resetFields()
        onlineInfoRef.value.resetFields()
        closeTabNavigate({ name: 'ReviewExperts' })
      } else {
        ElMessage.error(`保存草稿失败: ${res.msg || '未知错误'}`)
      }
    } catch (e) {
      console.error('保存草稿失败', e)
    }
  }

  // 提交表单
  const submit = async () => {
    const isOk = [false, false]
    await baseInfoRef.value.validate((valid) => {
      console.log(valid)

      isOk[0] = valid
    })
    await onlineInfoRef.value.validate((valid) => {
      console.log(valid, '2')
      isOk[1] = valid
    })
    if (isOk[0] && isOk[1]) {
      console.log('提交', userBaseInfo)
      // emeit('stop', true)
      if (reviewId.value) {
        const params = {
          id: reviewId.value,
          ...userBaseInfo,
        }
        updateReview(params).then((res) => {
          ElMessage({
            type: 'success',
            message: '修改成功',
          })
          closeTabNavigate({ name: 'ReviewExperts' })
        })
      } else {
        addReview(userBaseInfo).then((res) => {
          ElMessage({
            type: 'success',
            message: '新增成功',
          })
          closeTabNavigate({ name: 'ReviewExperts' })
        })
      }
    }
  }

  const reviewId = ref('')

  onMounted(() => {
    const id = (route.query.id as string) ?? ''
    const getType = route.query.getType ?? 2
    reviewId.value = id
    if (id) {
      getReviewsInfo({ id, getType }).then((res) => {
        for (const key in res.data) {
          userBaseInfo[key] = res.data[key]
        }
      })
    }
    try {
      const inputList = document.querySelectorAll('input.el-input__inner')
      const maxLength = 30
      inputList.forEach((input: any) => {
        input.maxLength = maxLength
      })
    } catch (error) {}
  })
</script>

<style scoped lang="scss">
  $margin-bottom: 20px;

  .margin-left20 {
    margin-left: $margin-bottom;
  }

  .buttonList {
    display: flex;
    justify-content: end;
    padding-bottom: $margin-bottom;
    border-bottom: 1px solid #edeff2;
    margin-bottom: $margin-bottom;
  }

  .card {
    .title {
      border-radius: 2px;
      border-left: 5px solid #1890ff;
      height: 28px;
      background: #f7f8f9;
      font-weight: 500;
      font-size: 14px;
      color: #606266;
      padding-left: 12px;
      line-height: 28px;
      margin-bottom: $margin-bottom;
    }
  }

  .margin-bottom0 {
    margin-bottom: 0 !important;
  }

  .margin-top20 {
    margin-top: 20px;
  }

  .demo-form-inline {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    grid-row-gap: 16px;
    grid-column-gap: 20px;

    .el-input {
      // --el-input-width: 323px;
    }

    .el-select {
      // --el-select-width: 323px;
    }

    :deep(.el-form-item__label) {
      padding: 0 5px 0 0;
    }

    :deep(.el-form-item) {
      margin-right: 0px;
      margin-bottom: 0px;
    }
  }

  .flexBox {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    grid-column-gap: 20px;
  }

  .formCard {
    border-radius: 4px;

    .formCardtitle {
      background: #e7f3ff;
      font-size: 12px;
      color: #7d8398;
      padding-left: 10px;
      height: 24px;
      line-height: 24px;
      border-radius: 4px 4px 0 0;
    }

    .cardForm {
      background: #f6fbff;
      padding: 20px;
      border-radius: 0 0 4px 4px;

      .el-input {
        // --el-input-width: 421px;
      }
    }
  }

  .demo-form {
    :deep(.el-form-item__content) {
      display: block;
    }

    .el-input {
      --el-input-width: 50%;
    }

    .el-select {
      --el-select-width: 50%;
    }
  }

  .last {
    margin-top: $margin-bottom;
  }
</style>
